// pages/storeShop/storeShop.js
const app = getApp()
var utils = require('../../utils/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabArr: {
            curHdIndex: 0,
            curBdIndex: 0
        },
		currentTab:0,
        isback:false,
        currentPage:1,
		goods: [],
		commment:[],
        classid:""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        that.setData({
            id:options.id
        })
		wx.getSystemInfo({
			success(res) {
				that.setData({
					resinfo: res.SDKVersion
				})
			}
		})
		// that.storeDetail();
		// that.classlist();
		// that.getCartNum();
       
    },
	onShow:function(){
		var that=this;
		that.setData({
			goods:[],
			commment: [],
			currentPage: 1,
		})
		that.storeDetail();
		that.commentsList();
		if (that.data.currentTab==-1){
			that.baogoodsList();
		}else{
		that.classlist();	
		}
		
		that.getCartNum();
	},
	/**
 * 生命周期函数--监听页面初次渲染完成
 */
	onReady: function () {
		var that = this;
		wx.getSystemInfo({
			success: function (res) {
				var query = wx.createSelectorQuery();
				console.log(query)
				query.select('#search-container').boundingClientRect(function (rect) {
					console.log(rect)
					that.setData({
						cateHeight: (res.windowHeight - rect.height)
					})
					console.log(that.data.cateHeight)
				}).exec();
			}
		})

	},
    // 获取购物车信息
    getCartNum:function(){
        var that = this;
        utils.http("/api/v1/cart/cart_list", {
            store_id: that.data.id,
        }, function (res) {
            if (res.state == 1) {
                that.setData({
                    cart_list: res.datas.cart_list,
                    cart_total: res.datas.cart_total,
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
	// 爆款
	baogoodsList: function () {
		var that = this;
		utils.http("/api/v1/goods/bao_goods_list", {
			store_id: that.data.id,
		}, function (res) {
			if (res.state == 1) {
				console.log(res)
				that.setData({
					goods: res.datas,
				})
				if(res.datas.length>0){
					that.setData({
						show_bao:1
					})
				}
				that.classlist();
			} else {
				utils.message(res.datas)
			}
		})
	},
    // //数量加，不能超过库存数
    onPrevTap(e) {
        var that = this;
        console.log(e);
        utils.showLoading();

        var ind = e.currentTarget.dataset.ind;
        utils.http("/api/v1/cart/add_cart", {
            goods_id: that.data.goods[ind].id,
        }, function (res) {
            utils.hideLoading();
            if (res.state == 1) {
                var cart_num = that.data.goods[ind].cart_num;
                that.data.goods[ind].cart_num = ++cart_num;
                that.setData({
                    goods: that.data.goods
                });
                that.getCartNum();
            } else {
                utils.message(res.datas)
            }
        })
    },
    // //数量减去不能少于1
    onNextTap(e) {
        var that = this;
        utils.showLoading();
        var ind = e.currentTarget.dataset.ind;
        utils.http("/api/v1/cart/reduce_cart", {
            goods_id: that.data.goods[ind].id,
        }, function (res) {
            utils.hideLoading();
            if (res.state == 1) {
                var cart_num = that.data.goods[ind].cart_num;
                that.data.goods[ind].cart_num = --cart_num;
                that.setData({
                    goods: that.data.goods
                });
                that.getCartNum();
            } else {
                utils.message(res.datas)
            }
        })
    },
    //店铺详情
    storeDetail: function () {
        var that = this;
        utils.http("/api/v1/store/store_detail", {
            store_id: that.data.id,
            latitude: wx.getStorageSync("localhost").latitude,
            longitude: wx.getStorageSync("localhost").longitude
        }, function (res) {
            if (res.state == 1) {
                that.setData({
                    detail: res.datas
                })
            } else {
                utils.message(res.datas)
            }
        })
    },
    //店铺分类
    classlist: function () {
        var that = this;
        utils.http("/api/v1/goods/class_list", {
            store_id: that.data.id,
        }, function (res) {
			console.log(res,"class_list");
            if (res.state == 1) {
                that.setData({
                    classlist: res.datas,
                    classid: res.datas[0].id,
                })
				if (that.data.show_bao !=1||that.data.currentTab!=-1){
					that.setData({
						currentTab: 0,
					})
					that.goodsList(that.data.currentPage, res.datas[0].id);
				}
            } else {
                utils.message(res.datas)
            }
        })
    },
    //商品列表
    goodsList: function (currentPage,classid) {
        var that = this;
        // utils.showLoading();
        utils.http("/api/v1/goods/goods_list", {
            page: currentPage,
            class_id:classid
        }, function (res) { 
            if (res.state == 1) {
                // utils.hideLoading();
                var allpost = that.data.goods;
                if (allpost == undefined) {
                    allpost = [];
                }
                for (var i in res.datas) {
                    allpost.push(res.datas[i])
                }
                if (res.datas.length < 10) {
                    that.setData({
                        tishi_title: '已加载全部',
                    });
                } else {
                    that.setData({
                        tishi_title: '加载更多',
                    });
                }
                that.setData({
                    goods: allpost,
                    ready: res.datas.length == 0 ? 1 : 2,
                })
                console.log(that.data.goods)
            } else {
                utils.message(res.datas)
            }
        })
    },
    //店铺评论列表
    commentsList: function (currentPage) {
        var that = this;
        // utils.showLoading();
        utils.http("/api/v1/store/store_comments_list", {
            page: currentPage,
            store_id: that.data.id,
        }, function (res) {
            if (res.state == 1) {
                // utils.hideLoading();
                var allpost = that.data.commment;
                if (allpost == undefined) {
                    allpost = [];
                }
                for (var i in res.datas) {
                    allpost.push(res.datas[i])
                }
                if (res.datas.length < 10) {
                    that.setData({
                        tishi_title: '已加载全部',
                    });
                } else {
                    that.setData({
                        tishi_title: '加载更多',
                    });
                }
                that.setData({
                    commment: allpost,
                    ready: res.datas.length == 0 ? 1 : 2,
                })
            } else {
                utils.message(res.datas)
            }
        })
    },

    //店铺收藏
    onIsColTap:function(e){
        var that=this;
        utils.http("/api/v1/store/make_col", {
            store_id: e.currentTarget.dataset.storeid,
        }, function (res) {
            if (res.state == 1) {
                that.storeDetail();
            } else {
                utils.message(res.datas)
            }
        })
    },
    //tab切换
    tab: function (e) {
        var that = this;
        var dataId = e.currentTarget.id;
        var obj = {};
        obj.curHdIndex = dataId;
        obj.curBdIndex = dataId;
        this.setData({
            tabArr: obj,
        })
        // if(dataId==0){
        // // that.goodsList(that.data.currentPage, that.data.classid);
        // }
        // if(dataId==1){
        
        // }
    },
    toAddOrder:function(){
        var that = this;
		//成功
	
		console.log(that.data.resinfo, "klsdjfklsdjfkl")
		var a = that.data.resinfo.split(".").join("");
		var str = "2.8.2"
		var b = str.split(".").join("");
		console.log(a, b)
		if (a < b) {
			console.log("基础库2.8.2以上才支持哈")
			utils.showSuccess("基础库2.8.2以上才支持哈", "none", false, 2000)
			//成功
			if (that.data.cart_total.total > 0) {
				wx.navigateTo({
					url: '/pages/placeorder/placeorder?store_id=' + that.data.id,
				})
			}
		} else {

			wx.requestSubscribeMessage({
				tmplIds: ["WlOZv5TjFsjUmFW1Rwo6ZxrD6H6y3_ygZ2Bh1aEMFc8"],
				success: function (res1) {
					console.log(res1)
					if (res1.WlOZv5TjFsjUmFW1Rwo6ZxrD6H6y3_ygZ2Bh1aEMFc8 == "accept") {
						//成功
						if (that.data.cart_total.total > 0) {
							wx.navigateTo({
								url: '/pages/placeorder/placeorder?store_id=' + that.data.id,
							})
						}

					} else {
						console.log("cuowu")
						//成功
						
					}

				},
				fail(err) {
					//失败
					console.error(err);
				}
			})
		}
       
    },

    //店铺分类切换
    swichNav:function(e){
        var that=this;
		console.log(that.data.currentTab)
		
        this.setData({
            currentTab: e.currentTarget.dataset.index,
            classid: e.currentTarget.dataset.id,
            currentPage:1,
            goods:[],
			bao_list:[]
        })
			if (that.data.currentTab == -1) {
				that.baogoodsList();
		}else{
			that.goodsList(that.data.currentPage, that.data.classid);
		}

    },
    //打开购物车
    onBindOpenTap:function(){
        var that=this;
        if(that.data.cart_total.total > 0){
            that.setData({
                isback:true
            }) 
        }
    },
    //关闭购物车
    bindCloseTap:function(){
        var that = this;
        that.setData({
            isback: false
        })
    },
    onShoppTap:function(){

    },
    /**
     * 生命周期函数--监听页面显示
     */

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },
    /**
     * 页面上拉触底事件的处理函数   scroll-view
     */
    bindscrolltolower: function (e) {
        var that = this;
        if (that.data.ready == 2) {
            var page = that.data.currentPage + 1
            that.setData({
                currentPage: page,
            })
            that.goodsList(page, that.data.classid);
            if (that.data.tabArr.curHdIndex==0){
                console.log(that.data.tabArr.curHdIndex)
            }
            if (that.data.tabArr.curHdIndex == 1) {
                that.commentsList(that.data.page)
            }
        }
    },
    //添加购物车
    addDetailCart: function(e) {
        var that = this;
        utils.showLoading();
        var ind = e.currentTarget.dataset.ind;
        var goods_id = that.data.cart_list[ind].goods_id;
        utils.http("/api/v1/cart/add_cart", {
            goods_id: goods_id,
        }, function (res) {
            if (res.state == 1) {
                that.getCartNum();
                // 循环当前商品列表
                 //更新商品列表数量
                var goodsList = that.data.goods;
                for (var i = 0; i < goodsList.length; i++) {
                    if (goodsList[i].id == goods_id) {
                        goodsList[i].cart_num = parseInt(goodsList[i].cart_num) + parseInt(1);
                    }
                };
                that.setData({
                    goods: goodsList,
                });
                utils.hideLoading();
            } else {
                utils.hideLoading();
                utils.message(res.datas)
            }
        })
    },
    //减少购物车详情中商品
    delDetailCart: function(e) {
        var that = this;
        utils.showLoading();
        var ind = e.currentTarget.dataset.ind;
        var goods_id = that.data.cart_list[ind].goods_id;
        utils.http("/api/v1/cart/reduce_cart", {
            goods_id: goods_id,
        }, function (res) {
            if (res.state == 1) {
                that.getCartNum();
                // 循环当前商品列表
                 //更新商品列表数量
                var goodsList = that.data.goods;
                for (var i = 0; i < goodsList.length; i++) {
                    if (goodsList[i].id == goods_id) {
                        goodsList[i].cart_num = parseInt(goodsList[i].cart_num) - parseInt(1);
                    }
                };
                that.setData({
                    goods: goodsList,
                });
                utils.hideLoading();
            } else {
                utils.hideLoading();
                utils.message(res.datas)
            }
        })

    },
    del_cart:function(){
        var that = this;
        utils.confirm('您确定要删除购物车中的全部商品吗？',function(res){
            if(res.confirm){
                utils.showLoading();
                utils.http("/api/v1/cart/empty_cart", {
                    store_id: that.data.id,
                }, function (res) {
                    if (res.state == 1) {
                        that.getCartNum();
                        // 循环当前商品列表
                         //更新商品列表数量
                        var goodsList = that.data.goods;
                        for (var i = 0; i < goodsList.length; i++) {
                            goodsList[i].cart_num = 0;
                        };
                        that.setData({
                            goods: goodsList,
                        });
                        that.bindCloseTap();
                        utils.hideLoading();
                    } else {
                        utils.hideLoading();
                        utils.message(res.datas)
                    }
                })

            }
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})